<?php

/**
 * 原型模式  
 * 
 * 相比正常创建一个对象 ( new Foo() )，首先创建一个原型，然后克隆它会更节省开销
 * 大数据量 ( 例如：通过 ORM 模型一次性往数据库插入 1,000,000 条数据 ) 。
 */
abstract class BookPrototype
{

    /**
     *
     * @var string
     */
    protected $title;

    /**
     *
     * @var string
     */
    protected $category;

    abstract public function __clone();

    public function getTitle(): string
    {
        return $this->title;
    }

    public function setTitle($title)
    {
        $this->title = $title;
    }
}

class FooBookPrototype extends BookPrototype
{

    /**
     *
     * @var string
     */
    protected $category = 'Foo';

    public function __clone()
    {}
}

class BarBookPrototype extends BookPrototype
{

    /**
     *
     * @var string
     */
    protected $category = 'Bar';

    public function __clone()
    {}
}

$fooPrototype = new FooBookPrototype();
$barPrototype = new BarBookPrototype();

for ($i = 0; $i < 10; $i ++) {
    $book = clone $fooPrototype;
    $book->setTitle('Foo Book No ' . $i);
}

for ($i = 0; $i < 5; $i ++) {
    $book = clone $barPrototype;
    $book->setTitle('Bar Book No ' . $i);
}